<?php
/**
 * 管理员管理
 * @author 江羿平<hugcolin@163.com>
 */

use Core\AdminController;
use Models\Admin;
class AdminController extends AdminController {


	/**
	 * 列表页
	 */
	public function index(){
		$admin = new Admin;

		if ($this->input->get('keyword')) {
			$admin->like('name', $this->input->get('keyword'));
		}

		$page = $admin->order_by('id desc')->paginate(20);

		$this->load->view('admin/admin/index', [
			'page' => $page
		]);
	}

	/**
	 * 添加页面
	 */
	public function add(){

		$this->load->library('form_validation');
		$this->form_validation->set_rules('name', '名称', 'required')
			->set_rules('account', '账号', 'required|is_unique[admins.account]')
			->set_rules('password', '密码', 'required');
		if ($this->form_validation->run()) {
			$admin = new Admin();
			$admin->load($this->input->post());
			$admin['password'] = encrypt($admin['password']);
			$admin->add();

			echo '<script>alert("添加成功");window.location.href="/admin/admin/index"</script>';
			exit;
		}
		
		$this->load->view('admin/admin/add');
	}

	/**
	 * 编辑页面
	 */
	public function edit($id){
		$admin = (new Admin)->find($id);
		if (!$admin) {
			show_404();
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('name', '名称', 'required');
		if ($this->form_validation->run()) {
			$admin['name'] = $this->input->post('name');

			if ($this->input->post('password')) {
				$admin['password'] = encrypt($admin['password']);
			}

			$admin->update();

			echo '<script>alert("保存成功");window.location.href="/admin/admin/index";</script>';
			exit;
		}
		
		$this->load->view('admin/admin/edit', [
			'admin' => $admin
		]);
	}

	public function change_status($id)
	{
		$status = $this->input->post('status');

		$admin = new Admin();
		if ($admin->find($id)) {
			$admin['status'] = $status;
			$admin->update();

			return $this->response([]);
		}

	}

	/**
	 * 修改密码
	 */
	public function password(){
		if($this->input->method() == 'post'){
			$oldpass = $this->input->post('old');
			$newpass = $this->input->post('new');
			$newpass2 = $this->input->post('new2');
			if(!$oldpass || !$newpass || !$newpass2){
				echo json_encode(array('code'=>2));
				exit;
			}
			if($newpass != $newpass2){
				echo json_encode(array('code'=>3));
				exit;
			}
			$admin = new Admin;
			$admin->find($this->session->admin_id);
			if($admin['password'] != encrypt($oldpass)){
				echo json_encode(array('code'=>1));
				exit;
			}
			$admin['password'] = encrypt($newpass);
			$admin->update($admin['id'],array('password'=>$admin['password']));
			echo json_encode(array('code'=>0));
		}else{
			$this->load->view('admin/admin/password');
		}
	}

}

